#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Function:
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Sets up user data directory.
	# - Allows automated moving of user data in DietPi. Automatically generates a symlink from /mnt/dietpi_userdata to target directory if needed.
	#
	# Usage:
	# - /boot/dietpi/func/dietpi-set_userdata SOURCE_DIRECTORY TARGET_DIRECTORY | Setup user data directory, move data if needed. If TARGET_DIRECTORY='auto', auto target location. Returns 1 if failed.
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Set_userdata'
	G_CHECK_ROOT_USER
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	EXIT_CODE=0

	# Grab input
	# - Remove trailing slashes
	SOURCE_DIRECTORY=${1%/}
	TARGET_DIRECTORY=${2%/}

	readonly FP_LOG='/var/log/dietpi-move_userdata.log'
	LOGFILE_OUTPUT_TEXT=
	FREESPACE_REQUIRED_SOURCE=0

	Run_Move_Data(){

		# Stop all running services
		/boot/dietpi/dietpi-services stop

		G_DIETPI-NOTIFY 2 "Moving your existing data from $SOURCE_DIRECTORY to $TARGET_DIRECTORY, please wait..."

		# Begin transfer
		if cp -a "$SOURCE_DIRECTORY/." "$TARGET_DIRECTORY/"; then

			# Remove source
			rm -R "$SOURCE_DIRECTORY"

			# Create symlink at /mnt/dietpi_userdata if required
			if [[ $TARGET_DIRECTORY != '/mnt/dietpi_userdata' ]]; then

				rm -Rf /mnt/dietpi_userdata
				ln -s "$TARGET_DIRECTORY" /mnt/dietpi_userdata

			fi

			# Apply dietpi:dietpi owner, used by some software titles like Syncthing and file servers to permit creating files and directories
			chown dietpi:dietpi "$TARGET_DIRECTORY"

			LOGFILE_OUTPUT_TEXT="Successfully moved your data from $SOURCE_DIRECTORY to $TARGET_DIRECTORY."

		else

			LOGFILE_OUTPUT_TEXT="Failed to copy $SOURCE_DIRECTORY/ to $TARGET_DIRECTORY."
			EXIT_CODE=1

		fi

		# Start services back up again
		/boot/dietpi/dietpi-services start

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////

	G_DIETPI-NOTIFY 3 'DietPi Updating user data location'
	G_DIETPI-NOTIFY 2 " - From : $SOURCE_DIRECTORY"
	G_DIETPI-NOTIFY 2 " - To   : $TARGET_DIRECTORY"
	G_DIETPI-NOTIFY 2 'Please wait...'

	# Sanity checks
	# - Check for both inputs
	if ! [[ $SOURCE_DIRECTORY && $TARGET_DIRECTORY ]]; then

		LOGFILE_OUTPUT_TEXT="Please provide a source ($SOURCE_DIRECTORY) and target ($TARGET_DIRECTORY) directory for input."
		EXIT_CODE=1

	# - Check if symlink is already pointing to target directory
	elif [[ $(readlink -f /mnt/dietpi_userdata) == "$TARGET_DIRECTORY" ]]; then

		LOGFILE_OUTPUT_TEXT="/mnt/dietpi_userdata has already been moved to $TARGET_DIRECTORY, nothing to do."

	# - Check if source directory exists
	elif [[ ! -d $SOURCE_DIRECTORY ]]; then

		LOGFILE_OUTPUT_TEXT="Source directory $SOURCE_DIRECTORY does not exist."
		EXIT_CODE=1

	# - Check for disallowed directory match
	elif [[ $SOURCE_DIRECTORY == "$TARGET_DIRECTORY" || $SOURCE_DIRECTORY == "$TARGET_DIRECTORY/"* || $TARGET_DIRECTORY == "$SOURCE_DIRECTORY/"* ]]; then

		LOGFILE_OUTPUT_TEXT="$SOURCE_DIRECTORY and $TARGET_DIRECTORY cannot be within each other. Disallowed directory match."
		EXIT_CODE=1

	# - Only allow full filepaths
	elif [[ $SOURCE_DIRECTORY != '/'* || $TARGET_DIRECTORY != '/'* ]]; then

		LOGFILE_OUTPUT_TEXT="Source ($SOURCE_DIRECTORY) and target directories ($TARGET_DIRECTORY) must be given with absolute path, e.g.: /mnt/drive1"
		EXIT_CODE=1

	else

		# Remove /mnt/dietpi_userdata symlink, if chosen as target
		[[ $TARGET_DIRECTORY == '/mnt/dietpi_userdata' && -L '/mnt/dietpi_userdata' ]] && rm /mnt/dietpi_userdata

		# Create target directory
		mkdir -p "$TARGET_DIRECTORY"

		# Ensure target directory supports POSIX permissions
		if ! G_CHECK_FS_PERMISSION_SUPPORT "$TARGET_DIRECTORY"; then

			LOGFILE_OUTPUT_TEXT="$TARGET_DIRECTORY does not support POSIX permissions. Transfer aborted."
			EXIT_CODE=1

		else

			# Check for sufficient free space in target directory
			# - "-m" => result in MiB actual disk usage, respecting disk block size, e.g. "144"
			# - Trailing slash required with "du" to correctly check symlink target in case
			FREESPACE_REQUIRED_SOURCE=$(du -sm "$SOURCE_DIRECTORY/" | mawk '{print $1}')
			if ! G_CHECK_FREESPACE "$TARGET_DIRECTORY" "$FREESPACE_REQUIRED_SOURCE"; then

				LOGFILE_OUTPUT_TEXT="Not enough free space in target directory $TARGET_DIRECTORY.\n - Required: $FREESPACE_REQUIRED_SOURCE MiB"
				EXIT_CODE=1

			else

				# Run, attempt to move data.
				Run_Move_Data

			fi

		fi

	fi

	#-----------------------------------------------------------------------------------
	# Print results and send to logfile
	if [[ $LOGFILE_OUTPUT_TEXT ]]; then

		# Failed
		if (( $EXIT_CODE )); then

			G_DIETPI-NOTIFY 1 "$LOGFILE_OUTPUT_TEXT"
			echo -e "[FAILED] $LOGFILE_OUTPUT_TEXT" > $FP_LOG

		# Ok
		else

			G_DIETPI-NOTIFY 0 "$LOGFILE_OUTPUT_TEXT"
			echo -e "[  OK  ] $LOGFILE_OUTPUT_TEXT" > $FP_LOG

		fi

	fi

	#-----------------------------------------------------------------------------------
	G_DIETPI-NOTIFY -1 $EXIT_CODE "$G_PROGRAM_NAME"
	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
